//获取应用实例
const app = getApp()
var template = require('../../utils/tabBarTemplate/tabBarTemplate.js');
var newcartlist=[];
//var globalCartlist=[];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _token:'',
    cartList:[],//购物车列表
    imgpath: '',//图片路径
    //编辑时 显示的状态
    cartPanel: false,
    delPanel: true,
    totalPrice:0,//显示合计
    _checkAll:false,//全选状态
    spec_arr:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.removeStorageSync("cartItems");
    var that = this;
    //tabbar菜单
    template.tabbar("tabBar", 2, this)//0表示第一个tabbar

    var _key = wx.getStorageSync("token");
    var imgpath = app.globalData.imgsPath;
   
    that.setData({
      _token: _key,
      imgpath: imgpath
    })

    var _list = wx.getStorageSync("cartItems");
  
    var _status = wx.getStorageSync("checkall");
    if (_list.length > 0) {
      newcartlist = _list;
    }
   
    
    that.getCartList();

  },
  //获取购物车列表
  getCartList:function(){
    var that = this;
    var _key = that.data._token;
    wx.request({
      url: app.globalData.httpsPath + '/cart/list',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        token: _key,
      },
      //请求后台数据成功  
      success: function (res) {
        var _cartlist = res.data.data;
        var _totalPrice = res.data.total_price;
        
        console.info(_totalPrice)
        
        // 隐藏加载框
        wx.hideLoading();
        console.info(_cartlist)
        that.setData({
          cartList   : _cartlist,
          totalPrice : _totalPrice
        })
      }
    })
  },
  //编辑
  operatingEidt:function(){
    this.setData({
      cartPanel: true,
      delPanel: false,
    })
  },
  //完成
  operatingComplete:function(){
    this.setData({
      cartPanel: false,
      delPanel: true,
    })
  },


  //合计数量
  getsumTotal: function () {
    var that = this;
    var sum = 0;
    var _list = that.data.cartList;
    console.info('购物车信息')
    console.info(_list)

    for (var i = 0; i < _list.length; i++) {
      if (_list[i].selected) {
        console.info('数量：'+_list[i].num,'价格：'+_list[i].price)
        sum += _list[i].num * _list[i].price
      }
    }
    console.info('合计：'+sum)
    //更新数据
    that.setData({
      totalPrice: sum.toFixed(2)
    })
    wx.setStorageSync('totalprice', sum.toFixed(2))
  },
  //数量添加
  addProd:function(e){
    var that = this;
    var cartItems = that.data.cartList;   //获取购物车列表
    var index = e.currentTarget.dataset.index; //获取当前点击事件的下标索引
    var _id = e.currentTarget.dataset.id; //获取当前点击事件的下标索引
    var _price = e.currentTarget.dataset.price;
    var prod_num = e.currentTarget.dataset.num;  //获取购物车里面的value值
    var _token = that.data._token;
   
    

    prod_num ++;

    wx.request({
      url: app.globalData.httpsPath + '/cart/increase',
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: {
        token: _token,
        id: _id
      },
      //请求后台数据成功  
      success: function (res) {
        console.info(res.data)
        if (res.data.status == true) {
          that.getCartList()
          var _total_price = res.data.total_price
          that.setData({
            totalPrice: _total_price
          })
         
        }
      }
    })
  },
  //数量减少
  reduceProd:function(e){
    var that = this;
    var cartItems = that.data.cartList;   //获取购物车列表
    var index = e.currentTarget.dataset.index; //获取当前点击事件的下标索引
    var _id = e.currentTarget.dataset.id; //获取当前点击事件的下标索引
    var _token = that.data._token;
    var prod_num = cartItems[index].num;  //获取购物车里面的value值
    var _price = e.currentTarget.dataset.price
   
    if(that.data.totalPrice<Number(_price)){
    
      return false   
    }
    if (prod_num == 1) {
      prod_num --;
      wx.showToast({
        icon: "none",
        title: '数量不能低于1'
      })
      cartItems[index].num = 1
    } else {
      prod_num --;
      wx.request({
        url: app.globalData.httpsPath + '/cart/decrease',
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: {
          token: _token,
          id: _id
        },
        //请求后台数据成功  
        success: function (res) {
          that.getCartList()
          if (res.data.status == true) {
            var _total_price = res.data.total_price
            that.setData({
              totalPrice: _total_price
            })
           
           
          } else {
            wx.showToast({
              icon: "none",
              title: res.data.msg
            })
            return 
          }
        }
      })
    }
  },
  //删除单个
  delCartprod:function(e){
    console.info(e);
    var that = this;
    var _key = that.data._token;
    var _id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '删除商品',
      content: '确认删除当前商品吗？',
      success(res) {
        if (res.confirm) {

          var selectedlist = wx.getStorageSync("cartItems");
          if (selectedlist.length > 0 ){
            selectedlist.forEach(function (i, index) {
              if (i.id == _id) {
                selectedlist.splice(index);
              }
            })
            wx.setStorageSync("cartItems", selectedlist)
          }
          wx.request({
            url: app.globalData.httpsPath + '/cart/del',
            method: 'POST',
            header: {
              'content-type': 'application/json'
            },
            data: {
              token: _key,
              id: _id,
            },
            //请求后台数据成功  
            success: function (res) {
              var total_price = res.data.total_price;
              if (res.data.status == true) {
                that.getCartList();
                that.setData({
                  totalPrice: total_price
                })

                
              }
            }
          })

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
    
  },
  //删除全部
  delAllProd:function(){
    var that = this;
    var _key = that.data._token;
    var cartItems = that.data.cartList
    var _checkAll = that.data._checkAll;
    if (_checkAll == false){
      wx.showToast({
        icon: "none",
        title: '请全部选中商品再进行清空!'
      })
    }else{
      wx.request({
        url: app.globalData.httpsPath + '/cart/del-all',
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: {
          token: _key
        },
        //请求后台数据成功  
        success: function (res) {
          console.info(res.data)
          if (res.data.status == true) {
            that.getCartList();
            wx.setStorageSync("cartItems")
            wx.setStorageSync('totalprice')
          }
        }
      })
    }
  },
  //去下单
  goOrder:function(){
    var that = this;
    wx.setStorageSync('totalprice',that.data.totalPrice)
    var cartItems = that.data.cartList;   //获取购物车列表
    
  
    if (cartItems.length == 0){
      wx.showToast({
        icon: "none",
        title: '请选择商品再进行去结算!'
      })
    }else{
      wx.navigateTo({
        url: '../confirmOrder/confirmOrder'
      })
    }
  },
})